package com.tsy.graduate.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.tsy.graduate.bean.*;
import com.tsy.graduate.constant.WxAppConstant;
import com.tsy.graduate.exception.BusinessException;
import com.tsy.graduate.httpdto.ObjectDataResponse;
import com.tsy.graduate.mapper.QuestionMapper;
import com.tsy.graduate.service.*;
import com.tsy.graduate.utils.DateUtils;
import com.tsy.graduate.utils.GsonUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@RestController
@Api("功能接口")
@RequestMapping("/feature")
public class FeatureController {

    @Autowired
    QuestionService questionService;

    @Autowired
    ExamService examService;

    @Autowired
    HomeworkService homeworkService;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    CourseService courseService;

    @Autowired
    LessonService lessonService;

    @Autowired
    CourseRecordService courseRecordService;

    @Autowired
    NotebookRecordService notebookRecordService;


    /**
     * @param type
     * @param exam
     * @return
     */
    @PostMapping("/editExam/{type}")
    @ApiOperation("编辑测验 exam")
    public ObjectDataResponse<Boolean> editExam(@PathVariable("type") Byte type,
                                                @RequestBody() Exam exam
    ) {
        if (type.equals(WxAppConstant.ACTION_TYPE_EDIT)) {
            if (exam.getId() == null || exam.getId() < 1) {
                throw new BusinessException(4000, "examId无效");
            }
            return new ObjectDataResponse<>(examService.updateById(exam));

        } else if (type.equals(WxAppConstant.ACTION_TYPE_DELETE)) {
            if (exam.getId() == null || exam.getId() < 1) {
                throw new BusinessException(4000, "examId无效");
            }
            exam.setIsDeleted(true);
            examService.updateById(exam);
            return new ObjectDataResponse<>(true);

        } else if (type.equals(WxAppConstant.ACTION_TYPE_ADD)) {
            if (exam.getTeacherId() == null || exam.getTeacherId() < 0
                    || exam.getCourseId() == null
                    || exam.getCourseId() < 0 ||
                    Strings.isNullOrEmpty(exam.getQuestionIds())) {
                throw new BusinessException(2000, "增加exam所需要的参数不全");
            }
            int timestamp = DateUtils.getCurrentTimestamp();
            exam.setUpdated(timestamp)
                    .setCreated(timestamp);
            String idMsg = examService.saveAndId(exam).toString();
            return new ObjectDataResponse<>(200, idMsg, true);
        }
        throw new BusinessException(4002, "type无效");

    }

    @PostMapping("/editCourse/{type}")
    @ApiOperation("编辑课程 course")
    public ObjectDataResponse<Boolean> editCourse(
            @RequestBody Course course,
            @PathVariable(value = "type") Byte type) {

        if (type.equals(WxAppConstant.ACTION_TYPE_DELETE)) {
            if (course.getId() == null || course.getId() < 0) {
                throw new BusinessException(2000, "删除必须要带上课程id");
            }
            return new ObjectDataResponse<>(
                    courseService.updateById(course.setIsDeleted(true))
            );
        }
        if (type.equals(WxAppConstant.ACTION_TYPE_ADD)) {

            if (Strings.isNullOrEmpty(course.getImgUrl())
                    || course.getTeacherId() == null || Strings.isNullOrEmpty(course.getTitle())
                    || Strings.isNullOrEmpty(course.getTextContent())) {
                throw new BusinessException(2000, "参数不全");
            }
            if (course.getId() != null) {
                throw new BusinessException(2000, "添加时不可指定id");
            }
            int timestamp = DateUtils.getCurrentTimestamp();
            course.setUpdated(timestamp)
                    .setCreated(timestamp);
            Long rst = courseService.saveAndId(course);
            return new ObjectDataResponse<>(200, rst.toString(), true);
        } else if (type.equals(WxAppConstant.ACTION_TYPE_EDIT)) {
            if (course.getId() == null || course.getId() < 0) {
                throw new BusinessException(2000, "参数不全");
            }
            int timestamp = DateUtils.getCurrentTimestamp();

            course.setUpdated(timestamp);

            return new ObjectDataResponse<>(courseService.updateById(course));

        }
        throw new BusinessException(20001, "type不在规定值中");

    }

    @PostMapping("/editHomewrok/{type}")
    @ApiOperation("编辑作业 homework")
    public ObjectDataResponse<Boolean> editHomework(@RequestBody(required = false)
                                                                Homework homework,
                                                    @PathVariable("type") Byte type
    ) {
        if (type.equals(WxAppConstant.ACTION_TYPE_EDIT)) {
            if (homework.getId() == null || homework.getId() < 1) {
                throw new BusinessException(4000, "homeworkId无效");
            }
            return new ObjectDataResponse<>(homeworkService.updateById(homework));

        } else if (type.equals(WxAppConstant.ACTION_TYPE_DELETE)) {
            if (homework.getId() == null || homework.getId() < 1) {
                throw new BusinessException(4000, "homeworkId无效");
            }
            homework.setIsDeleted(true);
            homeworkService.updateById(homework);
            return new ObjectDataResponse<>(true);

        } else if (type.equals(WxAppConstant.ACTION_TYPE_ADD)) {
            int timestamp = DateUtils.getCurrentTimestamp();

            homework.setUpdated(timestamp)
                    .setId(null)
                    .setCreated(timestamp);

            String idMsg = homeworkService.saveAndId(homework).toString();
            return new ObjectDataResponse<>(200, idMsg, true);
        }
        throw new BusinessException(4002, "type无效");
    }




    @PostMapping("/editLesson/{type}")
    @ApiOperation("编辑课程小节 lesson")
    public ObjectDataResponse<Boolean> editLesson(@RequestBody(required = false) Lesson lesson,
                                                  @PathVariable("type") Byte type
    ) {
        if (type.equals(WxAppConstant.ACTION_TYPE_EDIT)) {
            if (lesson.getId() == null || lesson.getId() < 1) {
                throw new BusinessException(4000, "lessonId无效");
            }

            return new ObjectDataResponse<>(lessonService.updateById(lesson));

        } else if (type.equals(WxAppConstant.ACTION_TYPE_DELETE)) {
            if (lesson.getId() == null || lesson.getId() < 1) {
                throw new BusinessException(4000, "lessonId无效");
            }
            lesson.setIsDeleted(true);

            lessonService.updateById(lesson);
            return new ObjectDataResponse<>(true);

        } else if (type.equals(WxAppConstant.ACTION_TYPE_ADD)) {
            int timestamp = DateUtils.getCurrentTimestamp();

            lesson.setUpdated(timestamp)
                    .setId(null)
                    .setImgUrl("wu")
                    .setCreated(timestamp);

            String idMsg = lessonService.saveAndId(lesson).toString();
            return new ObjectDataResponse<>(200, idMsg, true);
        }
        throw new BusinessException(4002, "type无效");
    }






    @GetMapping("/joinCourse")
    @ApiOperation("参加课程")
    public ObjectDataResponse<Boolean> joinCourse(@RequestParam() Long studentId,
                                                  @RequestParam() Long courseId,
                                                  @RequestParam() Long teacherId) {
        CourseRecord courseRecord = new CourseRecord();
        int timestamp = DateUtils.getCurrentTimestamp();

        courseRecord.setCourseId(courseId)
                .setStudentId(studentId)
                .setUpdated(timestamp)
                .setCreated(timestamp)
                .setTeacherId(teacherId);
        Boolean result = courseRecordService.save(courseRecord);
        if (!result) {
            throw new BusinessException(2001, "学生选课失败");
        }
        return new ObjectDataResponse<>(true);
    }

    /**
     * @param question
     * @return
     */
    @PostMapping("/uploadQuestion")
    @ApiOperation("上传题目")
    public ObjectDataResponse<Integer> addQuestion(@RequestBody() Question question) {
        String questionContent = question.getQuestionContent();
        String choices = question.getChoices();
        String choiceExplain = question.getChoiceExplain();
        Integer correctAnswer = question.getCorrectAnswer();
        if (Strings.isNullOrEmpty(questionContent) || Strings.isNullOrEmpty(choices)) {
            throw new BusinessException(10001, "关键参数不全");
        }
        if (correctAnswer == null || correctAnswer < 0 || correctAnswer > 3) {
            throw new BusinessException(10002, "correctAnswer 参数有问题");
        }
        int timestamp = DateUtils.getCurrentTimestamp();
        question.setQuestionContent(questionContent)
                .setChoiceExplain(choiceExplain)
                .setUpdated(timestamp)
                .setCreated(timestamp)
                .setCorrectAnswer(correctAnswer)
                .setChoices(choices);
        Integer id = questionMapper.insert(question);
        return new ObjectDataResponse<>(id);
    }

    /**
     * @param question
     * @return
     */
    @PostMapping("/addQuestionToHomework/{lessonId}")
    @ApiOperation("根据lessonid添加题目")
    public ObjectDataResponse<Boolean> addQuestionToHomework(
            @PathVariable("lessonId") Long lessonId,
            @RequestBody() Question question) {
        String questionContent = question.getQuestionContent();
        String choices = question.getChoices();
        String choiceExplain = question.getChoiceExplain();
        Integer correctAnswer = question.getCorrectAnswer();
        if (Strings.isNullOrEmpty(questionContent) || Strings.isNullOrEmpty(choices)) {
            throw new BusinessException(10001, "question关键参数不全");
        }
        if (correctAnswer == null || correctAnswer < 0 || correctAnswer > 3) {
            throw new BusinessException(10002, "correctAnswer 参数有问题");
        }
        int timestamp = DateUtils.getCurrentTimestamp();
        question.setUpdated(timestamp)
                .setCreated(timestamp)
                .setCorrectAnswer(correctAnswer)
                .setChoices(choices);
        Integer id = questionMapper.insert(question);
        Long questionId = question.getId();


        Homework homework = homeworkService.getOne(new QueryWrapper<Homework>()
                .lambda().eq(Homework::getLessonId,lessonId));
        if (homework==null){
            Lesson lesson = lessonService.getById(lessonId);
            if (lesson==null){
                throw new BusinessException(2002,"该lessonid不存在");
            }
            homework = new Homework();
            homework.setTitle("默认")
                    .setTeacherId(lesson.getTeacherId())
                    .setCreated(timestamp)
                    .setUpdated(timestamp)
                    .setLessonId(lessonId);
            List<Long> idList = new ArrayList<>();
            idList.add(questionId);

            homework.setQuestionIds(GsonUtils.encode(idList));
            homeworkService.save(homework);
            return new ObjectDataResponse<>(true);
        }
        List<Long> idList = new ArrayList<>();
        if (!Strings.isNullOrEmpty(homework.getQuestionIds())) {
            idList = GsonUtils.decodeList(homework.getQuestionIds(),Long.class);
        }
        idList.add(questionId);
        homework.setQuestionIds(GsonUtils.encode(idList));
        homeworkService.updateById(homework);
        return new ObjectDataResponse<>(true);
    }

    /**
     * @param question
     * @return
     */
    @PostMapping("/addQuestionToExam/{examId}")
    @ApiOperation("上传题目")
    public ObjectDataResponse<Boolean> addQuestionToExam(
            @PathVariable("examId") Long examId,
            @RequestBody() Question question) {
        String questionContent = question.getQuestionContent();
        String choices = question.getChoices();
        String choiceExplain = question.getChoiceExplain();
        Integer correctAnswer = question.getCorrectAnswer();
        if (Strings.isNullOrEmpty(questionContent) || Strings.isNullOrEmpty(choices)) {
            throw new BusinessException(10001, "question关键参数不全");
        }
        if (correctAnswer == null || correctAnswer < 0 || correctAnswer > 3) {
            throw new BusinessException(10002, "correctAnswer 参数有问题");
        }
        int timestamp = DateUtils.getCurrentTimestamp();
        question.setUpdated(timestamp)
                .setCreated(timestamp)
                .setCorrectAnswer(correctAnswer)
                .setChoices(choices);
        Integer id = questionMapper.insert(question);
        Long questionId = question.getId();
        Exam exam = examService.getById(examId);
        if (exam ==null){
            throw new BusinessException(2002,"不存在该id对应的exam");
        }
        List<Long> idList = GsonUtils.decodeList(exam.getQuestionIds(),Long.class);
        idList.add(questionId);
        String jsonStr = GsonUtils.encode(idList);
        System.out.println("Gson idList str = "+jsonStr);
        System.out.println("toString idList str = "+idList.toString());
        exam.setQuestionIds(GsonUtils.encode(idList));
        examService.updateById(exam);
        return new ObjectDataResponse<>(true);
    }


    @GetMapping("/updateNotebook")
    @ApiOperation("更新或添加错题记录  一道一道来")
    public ObjectDataResponse<Boolean> updateNotebook(@RequestParam() Long studentId,
                                                      @RequestParam() Long questionId,
                                                      @RequestParam() Integer wrongAnswerIndex,
                                                      @RequestParam(required = false, defaultValue = "无") String courseTitle,
                                                      @RequestParam(required = false, defaultValue = "无") String lessonTitle
    ) {
        NotebookRecord notebookRecord = notebookRecordService.getOne(new QueryWrapper<NotebookRecord>().lambda()
                .eq(NotebookRecord::getStudentId, studentId)
                .eq(NotebookRecord::getQuestionId, questionId));
        if (notebookRecord != null) {
            notebookRecord.setWrongAnswerIndex(wrongAnswerIndex);
            return new ObjectDataResponse<>(notebookRecordService.updateById(notebookRecord));
        }
        NotebookRecord newNotebookRecord = new NotebookRecord();
        int timestamp = DateUtils.getCurrentTimestamp();

        newNotebookRecord.setCourseTitle(courseTitle)
                .setWrongAnswerIndex(wrongAnswerIndex)
                .setLessonTitle(lessonTitle)
                .setQuestionId(questionId)
                .setUpdated(timestamp)
                .setCreated(timestamp)
                .setStudentId(studentId);
        return new ObjectDataResponse<>(notebookRecordService.save(newNotebookRecord));
    }

    @PostMapping("/updateNote")
    @ApiOperation("更新或添加错题解析")
    public ObjectDataResponse<Boolean> updateNotebookRecord(@RequestBody() Long id,
                                                            @RequestBody() String note) {
        if (id == null || id < 0) {
            throw new BusinessException(1111, "参数不全 id为空");
        }
        if (Strings.isNullOrEmpty(note)) {
            throw new BusinessException(1112, "错题笔记为空");
        }
        return new ObjectDataResponse<>(notebookRecordService.updateById(new NotebookRecord().setId(id).setNote(note)));
    }

}
